import { createRouter, createWebHashHistory } from 'vue-router'

// 导入登录和首页对应的组件
import Login from './components/MyLogin.vue'
import Home from './components/MyHome.vue'
// 导入菜单对应的组件
import Users from './components/menus/MyUsers.vue'
import Rights from './components/menus/MyRights.vue'
import Goods from './components/menus/MyGoods.vue'
import Orders from './components/menus/MyOrders.vue'
import Settings from './components/menus/MySettings.vue'
// 导入用户详情的组件
import UserDetails from './components/user/MyUserDetail.vue'

// 1.创建路由实例
const router = createRouter({
  // 指定路由模式
  history: createWebHashHistory(),
  // 设置路由规则
  routes: [
    { path: '/', redirect: '/home' },
    { path: '/login', component: Login },
    // Home 组件的路由规则
    {
      path: '/home', component: Home, redirect: '/home/users', children: [
        { name: 'users', path: 'users', component: Users },
        { name: 'rights', path: 'rights', component: Rights },
        { name: 'goods', path: 'goods', component: Goods },
        { name: 'orders', path: 'orders', component: Orders },
        { name: 'settings', path: 'settings', component: Settings },
        // 用户详情页的路由规则，开启 props 传参
        { name: 'userDetails', path: 'users/:id', component: UserDetails, props: true }
      ]
    },
  ],
})

// 2.设置路由守卫
router.beforeEach((to, from, next) => {
  // 访问的是登录或者注册页，直接放行
  if (to.path === '/login' || to.path === '/register') {
    next()
  } else {
    // 获取token
    const tokenStr = localStorage.getItem('token')
    if (!tokenStr) {
      // token五为空说明没有登录，跳转登录页
      next('/login')
    } else {
      // token不为空直接放行
      next()
    }
  }
})

// 3.共享路由实例对象
export default router
